<template>
  <div class='app-container'>
    <div style="margin-bottom: 12px">
      <!-- 表格 -->
      <el-table class="table" ref="nodeTable"
                :data="gridDataSource" v-loading.lock="gridDataIsLoading"
                element-loading-text="数据加载中..." border fit highlight-current-row>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table class="table" ref="taskTable" :data="props.row.tasks"
                      element-loading-text="数据加载中..." border fit highlight-current-row>
              <el-table-column label="作业ID">
                <template slot-scope="scope">
                  {{scope.row.taskid}}
                </template>
              </el-table-column>
              <el-table-column label="作业名称">
                <template slot-scope="scope">
                  {{scope.row.taskname}}
                </template>
              </el-table-column>
              <el-table-column label="作业状态">
                <template slot-scope="scope">
                  <el-tag type='danger' close-transition v-if="scope.row.taskstatus==1">已停止
                  </el-tag>
                  <el-tag type='success' close-transition v-if="scope.row.taskstatus==0">运行中
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="执行成功计数">
                <template slot-scope="scope">
                  <el-tag type='success'>{{ scope.row.taskexcutedcount }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="执行失败计数">
                <template slot-scope="scope">
                  <el-tag type='danger'>{{ scope.row.taskerrorcount }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="作业最后执行时间">
                <template slot-scope="scope">
                  {{scope.row.tasklastruntime}}
                </template>
              </el-table-column>
              <el-table-column label="预计下次执行时间">
                <template slot-scope="scope">
                  {{scope.row.tasknextruntime}}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="primary" @click="startTask(scope.row)">开始任务</el-button>
                  <el-button size="small" type="danger" @click="stopTask(scope.row)">停止任务</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="节点ID" width="240">
          <template slot-scope="scope">
            {{scope.row.nodeid}}
          </template>
        </el-table-column>
        <el-table-column label="节点名称" width="240">
          <template slot-scope="scope">
            {{scope.row.nodename}}
          </template>
        </el-table-column>
        <el-table-column label="运行状态" width="150">
          <template slot-scope="scope">
            <el-tag type='success' close-transition v-if="scope.row.noderunstate==1">运行中
            </el-tag>
            <el-tag type='danger' close-transition v-else>已停止
            </el-tag>
          </template>
        </el-table-column>
        <!--<el-table-column label="节点资源占用" width="150">-->
        <!--<template slot-scope="scope">-->
        <!--{{scope.row.nodeInfo.nodeip}}-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column label="最后心跳时间" width="150">
          <template slot-scope="scope">
            {{scope.row.nodelastheartbeat}}
          </template>
        </el-table-column>
        <el-table-column label="执行任务数" width="150">
          <template slot-scope="scope">
            <el-tag type='success'> {{scope.row.nodeExcuteingTaskCount}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="已停止任务数" width="150">
          <template slot-scope="scope">
            <el-tag type='danger'> {{scope.row.nodeUnExcuteingTaskCount}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button icon="edit" size="small" type="primary" @click="addTask(scope.row)">添加任务</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 指定任务 -->
    <el-dialog title='指定任务' :visible.sync='taskSelDialogOpend'>
      <div class="good-transfer">
        <el-transfer v-model="selectedTask" :titles="['未选任务', '已选任务']" :props="{ key: 'taskid', label: 'taskname'}"
                     :data="allTasks"></el-transfer>
      </div>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleTaskSelSubmit'>确定</el-button>
        <el-button @click='taskSelDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'node',
    data() {
      return {
        gridDataSource: [],
        gridDataIsLoading: false,
        currentNodeTask: [],
        taskSelDialogOpend: false,
        selectedTask: [],
        allTasks: [],
        selectedNode: null,
        taskStateDialogOpend: false,
        websock: null
      };
    },
    created() {
      this.refreshData();
      this.initWebSocket();
    },
    methods: {
      /**
       * 刷新数据
       */
      refreshData() {
        this.gridDataIsLoading = true;
        this.$http.get('/TaskPlatform/Node/GetNodeMonitorInfos').then((response) => {
          if (response.data.isSuccess) {
            this.gridDataSource = response.data.nodeMonitorInfos;
          }
          this.gridDataIsLoading = false;
        }).catch(() => {
          this.gridDataIsLoading = false;
        });
      },
      openTaskStateDialog(node) {
        this.selectedNode = node;
        this.$http.get('/TaskPlatform/TaskState/GetNodeTask', {
          params: {
            nodeid: this.selectedNode.nodeInfo.nodeid
          }
        }).then((response) => {
          if (response.data.isSuccess) {
            this.currentNodeTask = response.data.taskStates;
            this.taskStateDialogOpend = true;
          }
        });
      },
      /**
       * 添加任务
       */
      addTask(node) {
        this.selectedNode = node;
        this.$http.get('/TaskPlatform/TaskState/GetAllTaskState', {
          params: {
            nodeid: this.selectedNode.nodeid
          }
        }).then((response) => {
          if (response.data.isSuccess) {
            this.selectedTask = [];
            this.currentNodeTask = response.data.taskStates;
            response.data.taskStates.forEach((item) => {
              this.selectedTask.push(item.taskid);
            });

            this.$http.get('/TaskPlatform/TaskConfig/GetAllTaskConfig').then((response) => {
              if (response.data.isSuccess) {
                this.allTasks = response.data.taskConfigList;
                this.taskSelDialogOpend = true;
              }
            });
          }
        });
      },
      handleTaskSelSubmit() {
        let stateList = [];
        this.selectedTask.forEach((task) => {
          stateList.push({
            nodeId: this.selectedNode.nodeid,
            taskid: task,
            taskstatus: 1,
            tasknextruntime: new Date(),
            tasklastruntime: new Date()
          });
        });
        this.$http.post('/TaskPlatform/TaskState/UpdateNodeTaskStates', stateList, {
          params: {
            nodeid: this.selectedNode.nodeid
          }
        }).then(() => {
          this.taskSelDialogOpend = false;
        });
      },
      startTask(task) {
        if (task.taskerrorcount > 0) {
          this.$confirm("开始任务会将错误计数清零, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.$http.post('/TaskPlatform/TaskCommand/StartTask', task).then(() => {
            });
          });
        } else {
          this.$http.post('/TaskPlatform/TaskCommand/StartTask', task).then(() => {
          });
        }
      },
      stopTask(task) {
        console.log(task);
        this.$http.post('/TaskPlatform/TaskCommand/StopTask', task).then(() => {
        });
      },
      initWebSocket() {
        let socketKey = {
          "clientNo": "workmanager",
          "clientType": "taskoss"
        };
        let clientInfo = {
          "clinetKey": JSON.stringify(socketKey)
        };
        this.$http.post('/Jwt/GetJwt/websocket', clientInfo).then((response) => {
          if (response.data.isSuccess) {
            console.log(response);
            let wstoken = response.data.token;
            let wsuri = process.env.WS_API + "/TaskPlatform?token=" + wstoken;
            this.websock = new WebSocket(wsuri);
            this.websock.onmessage = this.websocketonmessage;
            this.websock.onclose = this.websocketclose;
          }
        });
      },
      // 数据接收
      websocketonmessage(e) {
        let redata = JSON.parse(e.data);
        if (redata !== null && redata !== undefined) {
          if (redata.MessageType === "updatenodestate") {
            let pushednodestate = JSON.parse(redata.Data);
            if (pushednodestate) {
              let findedindex = this.gridDataSource.findIndex((item) => {
                return item.nodeid === pushednodestate.nodeid;
              });
              if (findedindex !== -1) {
                let findednode = this.gridDataSource[findedindex];
                if (findednode) {
                  findednode.noderunstate = pushednodestate.noderunstate;
                  findednode.nodelastheartbeat = pushednodestate.nodelastheartbeat;
                }
              }
            }
          }
          if (redata.MessageType === "updatetaskstate") {
            let pushedtaskstate = JSON.parse(redata.Data);
            if (pushedtaskstate) {
              let findedindex = this.gridDataSource.findIndex((item) => {
                return item.nodeid === pushedtaskstate.nodeId;
              });
              if (findedindex !== -1) {
                let findednode = this.gridDataSource[findedindex];
                if (findednode) {
                  let taskindex = findednode.tasks.findIndex((task) => {
                    return task.taskid === pushedtaskstate.taskid;
                  });
                  if (taskindex !== -1) {
                    let findedtask = findednode.tasks[taskindex];
                    if (findedtask) {
                      findedtask.taskstatus = pushedtaskstate.taskstatus;
                      findedtask.tasknextruntime = pushedtaskstate.tasknextruntime;
                      findedtask.tasklastruntime = pushedtaskstate.tasklastruntime;
                      findedtask.taskexcutedcount = pushedtaskstate.taskexcutedcount;
                      findedtask.taskerrorcount = pushedtaskstate.taskerrorcount;
                    }
                  }
                }
              }
            }
          }
        }
      },
      // 数据发送
      websocketsend(agentData) {
        this.websock.send(agentData);
      },
      // 关闭
      websocketclose(e) {
        console.log("connection closed (" + e.code + ")");
      },
      SendMessage(message) {
        // 若是ws开启状态
        if (this.websock.readyState === this.websock.OPEN) {
          this.websocketsend(message);
        } else if (this.websock.readyState === this.websock.CONNECTING) {
          let that = this;// 保存当前对象this
          setTimeout(function () {
            that.websocketsend(message);
          }, 300);
        } else {
          this.initWebSocket();
          let that = this;// 保存当前对象this
          setTimeout(function () {
            that.websocketsend(message);
          }, 500);
        }
      }
    },
    beforeDestroy() {
      if (this.websock) {
        this.websock.close();
      }
    },
    computed: {
      GridPageList() {
        if (this.gridDataSource && this.gridDataSource.length > 0) {
          if (this.startIndex > 0 && this.endIndex > 0) {
            return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
          } else {
            return [];
          }
        } else {
          return [];
        }
      },
      dataCount() {
        if (this.gridDataSource) {
          return this.gridDataSource.length;
        } else {
          return 0;
        }
      }
    }
  };
</script>
<style>


  .table {
    height: 100%;
    overflow: auto;

  }

  .taskstate-wrapper {
    background-color: #ffffff;
    padding: 5px;
    box-shadow: 1px 1px 10px #888888;
    margin-bottom: 12px;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>



